<?php
/*
 * 支付回调
 */
namespace Mobile\Controller;

use Common\Service\PromoteService;
use Mobile\Model\orderModel;
use Mobile\Model\moneylogModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\gradeModel;//用户等级
use Mobile\Model\goodsModel;

use Mobile\Controller\PaywechatController;

class OrdercallbackController extends BaseController {

    public $orderModel;
    public $moneylogModel;
    public $gradeModel;
    public $goodsModel;
    public $payModel;
    public $grade_arr;
    public $areaModel;
    
    public function __construct($option='') {
        parent::__construct($option);
        $this->orderModel = new orderModel();
        $this->moneylogModel = new moneylogModel();
        $this->gradeModel = new gradeModel();
        $this->goodsModel = new goodsModel();
        $this->payModel = M('pay');
        $this->grade_arr = $this->_get_gradename();
        $this->areaModel = M('area');
    }
    protected function _get_gradename(){
        $where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
        $new_grade = array();
        foreach($grade_list as $k=>$v){
            $new_grade[$v['grade_id']] = $v['grade_name'];
        }
        return $new_grade;
    }
    //更改订单状态
    /*
     * $xml_arr 微信传过来的参数
     * $pay_type 1微信支付,
     */
    public function _changeOrder($order,$pay_type,$xml_arr=NULL,$alipayArr=null){
       
        if(empty($order)){
            return false;
        }
    
        if($order['pay_money']<=0){
            //return false;
            //站内币支付也分佣金
        }
        
        $where = array(
            "order_id" => $order['order_id']
        );
    
        //已支付
        if($order['checked'] == 1){
            //无需再次支付
            return false;
        }
    
        $order_data = array(
            "checked" => 1,
            "pay_type" => $pay_type,//支付方式 1微信支付2
        );
        
        if($order['is_delivery']==0 && ($order['order_type']==1 || $order['order_type']==2)) {
            $order_data['checked'] = 2;
        }
        
        if(!empty($xml_arr)){
            $order_data['bank_type'] = $xml_arr['bank_type'];
            //银行列表: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_2  CTF 财付通
            $order_data['transaction_id'] = $xml_arr['transaction_id'];//来自腾讯的外部订单号
            $order_data['pay_time'] = date("Y-m-d H:i:s",strtotime($xml_arr['time_end']));//支付时间
            $order_data['trade_type'] = $xml_arr['trade_type'];//交易类型 JSAPI、NATIVE、APP
        }elseif(!empty($alipayArr)){
            //TODO:支付宝支付
            //站内币支付
            //$order_data['pay_time'] = date("Y-m-d H:i:s");//支付时间
           // $order_data['trade_type'] = '';//交易类型 
            //$order_data['checked'] = 1;
            $order_data['pay_time'] = $alipayArr['gmt_payment'];
            $order_data['transaction_id'] = $alipayArr['trade_no'];
            $order_data['buyer_logon_id'] = $alipayArr['buyer_email'];
            $order_data['buyer_user_id'] = $alipayArr['buyer_id'];
        }else{
            //hm支付TODO
            $order_data['pay_time'] = date("Y-m-d H:i:s");//皇玛支付成功的时间TODO
			
        }
        
        $order_res = $this->orderModel->editOrder($where, $order_data);
    
        if($order_res===false){
            return false;//更改状态失败
        }
        $goods_info = unserialize($order['goods']);
        $jinhuo_nums = 0;
        foreach ($goods_info as $k=>$v){
            //更改商品销量,库存
            $where_g = array(
                "goods_id" => $v['goods_id'],
            );
            $goods_kucun = array(
                "sale_real" => array("exp","sale_real+".$goods_info[$k]['num']),
                "stock" => array("exp","stock-".$goods_info[$k]['num']),
                "sale_all" => array("exp","sale_real+sale_basic"),
            );
            $kucun = $this->goodsModel->editGoods($where_g, $goods_kucun);
            
            $jinhuo_nums += $v['num'];
        
        }
        $this->memberModel->where(array("uid"=>$order['uid']))->setInc('totalxf_money',$order['order_cashmoney']);//重消
        $order['pay_time'] = $order_data['pay_time'];
        $order['pay_type'] = $pay_type;
        $order['checked'] = 1;
    
        $uid = $order['uid'];
        $memberinfo = $this->getMemberInfobyUid($uid);//再次从数据库获取信息
        if(empty($memberinfo)){
            return false;
        }
        $this->memberModel->where(array('uid'=>$memberinfo['uid']))->setInc('jinhuo_nums',$jinhuo_nums);
        
        if($order['order_type']==1) {
            //报单订单
            $this->_handleBaodan($order);
        }
        if($order['order_type']==2) {
            $this->_handleBuhuo($order);
        }
        
     
        if(!$order['order_type']) {
            /*
            * 报单人的ID，用于后期统计业绩
            */
            $this->orderModel->where(array('order_id'=>$order['order_id']))->setField('baodan_uid',$memberinfo['uid']);
            $this->_fenyongLingshou($order, $memberinfo);
        }
        //分佣金处理
        PromoteService::S()->processingOrders($order['order_id']);
        //$this->_chuli_shengji($memberinfo);
        return true;//返回真
    }
    

    /*
     *处理新申请的代理
     */
    public function handelApply ($apply) {
        $memberinfo = $this->memberModel->where(array('uid'=>$apply['uid']))->find();
        $areaModel = M('area');
        $area = $areaModel->where(array('area_id'=>$apply['area_id']))->find();

        //设置代理区域
        $this->memberModel->where(array('uid'=>$area['uid']))->setField('area_id',$apply['area_id']);
        
        if($apply['type']==1) {//代理申请
            
        }elseif($apply['type']==2) {//加盟申请

        }
        //调整等级
        if($area['grade_id']>$memberinfo['grade_id']) {
            $this->memberModel->where(array('uid'=>$memberinfo['uid']))->setField('grade_id',$area['grade_id']);
            $this->_shengjiMsg($memberinfo, $memberinfo['grade_id'], $area['grade_id']);
        }
        
        //添加库存
        core_moneylog($memberinfo['uid'],$area['money'],4,'(代理/加盟)库存');

        //TODO 分佣
    }

    /*
     * 补货订单
     */
    protected function _handleBuhuo ($order) {
        if($order['order_type']!=2) {
            return false;
        }

        //补货 上级出库存 钱结算给上级
        $memberinfo = $this->memberModel->where(array('uid'=>$order['uid']))->find();
        $area = $this->areaModel->where(array('uid'=>$memberinfo['area_id']))->find();
        $parent = $area;
        //找到上级区域代理
        while(!empty($parent)) {
            $parent = $this->areaModel->where(array('area_id'=>$parent['parentid']))->find();
            if($parent['is_sale']) {
                break;
            }
        }
        if(!empty($parent)) {
            core_moneylog($memberinfo['uid'],$order['stock_money'],4,'补货入库存',$order);
            core_moneylog($parent['uid'],-$order['stock_money'],4,'下级补货出库存',$order);
            
            core_moneylog($parent['uid'],-$order['pay_orgmoney'],1,'下级补货收入',$order);
        }
    }


    /*
     * 处理报单订单
     */
    protected function _handleBaodan ($order,$new=true) {
        if($order['order_type']!=1) {
            return false;
        }
        
       if($new) {
           $refer = $this->memberModel->where(array('uid'=>$order['uid']))->find();
            $datainfo = json_decode($order['data_info'],true);
            //如果是新用户先添加用户
            $userinfo = $this->memberModel->where(array('mobile'=>$datainfo['baodan_mobile']))->find();
            if(!$userinfo) {
                //检查身份证
                $idcard = $datainfo['idcard'];
                $len = strlen($idcard);
                if($len != 18){
                   // return_json(1,"身份证号码填写错误,请重新填写");
                }
                $pass = substr($idcard, -6);
                $new = array(
                    'mobile' => $datainfo['baodan_mobile'],
                    'realname' => $datainfo['realname'],
                    'bzj_money' => $order['bzj_money'],
                    'pxf_money' => $order['pxf_money'],
                    'idcard' => $datainfo['idcard'],
                    'password' => md5($pass.C('SALT')),
                    'refer_uid' => $refer['uid'],
                    'refer_nickname' => $refer['realname']?$refer['realname']:$refer['nickname'],
                    'create_time' => date('Y-m-d H:i:s'),
                );
                $order['baodan_uid'] = $this->memberModel->add($new);
            }else{
                $order['baodan_uid'] = $userinfo['uid'];
                $save = array(
                    'bzj_money' => $userinfo['bzj_money']+$order['bzj_money'],
                    'pxf_money' => $userinfo['pxf_money']+$order['pxf_money'],
                );
                $this->memberModel->where(array('uid'=>$userinfo['uid']))->save($save);
            }

            if($order['is_delivery']==0) {
                //报单的库存给新报用户
                $content = "【报单】{$order['order_title']}";
                if($order['sj_gnums']>0) {
                    $this->_addMoneyLog($order['baodan_uid'], $order['sj_gnums'], $content, $order, 0, '', 4);
                }
            }
            $userinfo = $this->memberModel->where(array('uid'=>$order['baodan_uid']))->find();

            //等级ID
            $grade_id = $datainfo['grade_id'];
            $userinfo['grade_id'] = $grade_id;

            $this->memberModel->where(array('uid'=>$order['baodan_uid']))->setField('grade_id',$grade_id);

            
       }else{
           $userinfo = $this->memberModel->where(array('uid'=>$order['uid']))->find();
           $refer = $this->memberModel->where(array('uid'=>$userinfo['refer_uid']))->find();
           
            
            $content = "【报单】{$order['order_title']}";
            if($order['sj_gnums']>0) {
                $this->_addMoneyLog($order['uid'], $order['sj_gnums'], $content, $order, 0, '', 4);
            }
       }
       
       /*
        * 报单人的ID，用于后期统计业绩
        */
       $this->orderModel->where(array('order_id'=>$order['order_id']))->setField('baodan_uid',$userinfo['uid']);
        
       
       
       
        $this->_fenyong($order, $userinfo);
        
        
    }

    /* $type==1 普通会员消费订单 $type==2 申请代理的apply */
    protected function _sharePrize ($order,$type) {
        $uid = $order['uid'];
        if($type==1) {

        }
    }


    public function _fenyong ($order,$memberinfo) {
        
        $score = $order['order_cashmoney'];
        $this->_addMoneyLog($memberinfo['uid'], $score, $order['order_title'], $order, '', '', 2);
        $this->_shouruTmp($memberinfo, $order, $score, $order['order_title'], 2);
        
        
        $num = $order['sj_gnums'];
        $floor = 1;
        $refer = $this->memberModel->where(array('uid'=>$memberinfo['refer_uid']))->find();
        while(!empty($refer)) {
            if($refer['grade_id']!=1) {
                if($floor==1) {
                    $money = $this->_getChajia($order, $memberinfo, $refer);
                
                    if($money==0 && $refer['grade_id']<4){
                        $money = 0;
                        //一次性返利（低推高奖励）
                        if($order['order_type']==1 && $memberinfo['grade_id']>=$refer['grade_id']) {
                            $money = $num*10;
                        }
                    }

                    if($money==0 && $refer['grade_id']>=4){
                        $money = $num*20;
                    }
                }else{
                    if($refer['grade_id']>=4){
                        $money = $num*10;
                    }else{
                        $money = 0;
                    }
                }
                if($money>0) {
                    $content = "[第{$floor}级奖励]".$order['order_title'];
                    $this->_addMoneyLog($refer['uid'], $money, $content, $order, $floor, '', 1);
                    $this->_shouruTmp($refer, $order, $money, $content, 1);
                }
                
                $floor++;
            }
            if($floor>2) {
                break;
            }
            $refer = $this->memberModel->where(array('uid'=>$refer['refer_uid']))->find();
        }
    }
    
    public function _fenyongLingshou ($order,$memberinfo) {
        $num = $order['sj_gnums'];
        $floor = 1;
        $refer = $this->memberModel->where(array('uid'=>$memberinfo['refer_uid']))->find();
        while(!empty($refer)) {
            if($refer['grade_id']!=1) {
                if($floor==1) {
                    $money = $this->_getChajia($order, $memberinfo, $refer);
                    $content = "[第{$floor}级奖励]".$order['order_title'];
                    $this->_addMoneyLog($refer['uid'], $money, $content, $order, $floor, '', 1);
                    $this->_shouruTmp($refer, $order, $money, $content, 1);
                }
                $floor++;
            }
            if($floor>1) {
                break;
            }
            $refer = $this->memberModel->where(array('uid'=>$refer['refer_uid']))->find();
        }
    }
    
    protected function _getChajia ($order,$memberinfo,$refer) {
        if($memberinfo['grade_id']>=$refer['grade_id']){
            return 0;
        }
        $goodslist = unserialize($order['goods']);
        $chajia = 0;
        foreach ($goodslist as $goods){
            $chajia += ($goods["grade{$memberinfo['grade_id']}_price"]-$goods["grade{$refer['grade_id']}_price"])*$goods['num'];
        }
        return $chajia>0?$chajia:0;
    }

    /*
     * 用户升级逻辑
     */
    protected function _chuli_shengji($memberinfo) {
        $memberinfo = $this->memberModel->where(array('uid'=>$memberinfo['uid']))->find();
        $refer_info = $memberinfo;
        $floor = 1;
        while(!empty($refer_info)){
            $this->_shengji($refer_info);
            $refer_uid = $refer_info['refer_uid'];//上一级的uid
            $refer_info = $this->getMemberInfobyUid($refer_uid);//上一级的信息
            $floor++;
            if($refer_info['uid'] == $memberinfo['uid']){
                break;//死循环,中断
            }
        }
    }
  
    protected function _shengji($memberinfo) {
        
        $oldgrade = $newgrade = $memberinfo['grade_id'];
        if($oldgrade==5) {
            return false;
        }
        //当月消费累计升级：月累计到达相应的相应的金额自动升级相应级别
        $start = date('Y-m-01 00:00:00');
        $end = date('Y-m-01 00:00:00', strtotime('+1 month'));
        $mymonty = _getMyMoney($memberinfo['uid'], $start, $end);
        if($mymonty>=95020) {
            $newgrade = 5;
        }elseif($mymonty>=34200) {
            $newgrade = 4;
        }elseif($mymonty>=12900) {
            $newgrade = 3;
        }elseif($mymonty>=2980) {
            $newgrade = 2;
        }
        if($newgrade>$oldgrade) {
            $this->memberModel->where(array('uid'=>$memberinfo['uid']))->setField('grade_id',$newgrade);
            $this->_shengjiMsg($memberinfo, $oldgrade, $newgrade);
            $oldgrade = $newgrade;
        }
        
        if($oldgrade<2) {
            return false;
        }
        $refermoney = getReferMoney($memberinfo['uid']);

        if($refermoney>=156200) {
            $newgrade = 5;
        }elseif($refermoney>=53600) {
            $newgrade = 4;
        }elseif($refermoney>=14900) {
            $newgrade = 3;
        }
        
        if($newgrade>$oldgrade) {
            $this->memberModel->where(array('uid'=>$memberinfo['uid']))->setField('grade_id',$newgrade);
            $this->_shengjiMsg($memberinfo, $oldgrade, $newgrade);
        }
        
    }
    
    protected function _shengjiMsg($userinfo,$old,$new){
    
        $grade_arr = $this->grade_arr;
    
        $c = M("actionlog");
        $change2['log_type'] = 1;
        $change2['action_username'] = 'system';
        $change2['target_uid'] = $userinfo["uid"];
        $change2['target_username'] = $userinfo["realname"]?$userinfo["realname"]:$userinfo["nickname"];
    
        $change2['from_data'] = $old;
        $change2['to_data'] = $new;
        $change2['create_time'] = date('Y-m-d H:i:s');
        $change2['content'] = "(系统调整)".$grade_arr[$old]."->".$grade_arr[$new];
        $c->data($change2)->add();
        
        
        //设置更新最新升级时间
        $this->memberModel->where(array('uid'=>$userinfo['uid']))->setField('upgrade_time',$change2['create_time']);
         
        //发送模板消息
        $msg = $this->_sendsjmsgtmp($userinfo,$old,$new);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    /*
     * 升级消息
     *
     */
    protected function _sendsjmsgtmp($userinfo,$old,$new){
    
        $grade_arr = $this->grade_arr;
    
        $tmp_id = $this->tmpl['DENG_JI']['tmp_id'];
        $color = $this->tmpl['DENG_JI']['color'];
    
     //   $url = "http://123.taojiuren.cn/mobile/user/grade/";
     //   $footer ='\\n'."点击查看详情...";
        $url = $footer = "";
        
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("恭喜,你的等级已提升~".'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($grade_arr[$old]),//原先等级
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($grade_arr[$new]),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }


        //支付回调
    public function callback(){
    
        $order_id = get('order_id');
        if(!$order_id){
            echo "fail";exit;
        }
    
        $where = array(
            "order_id" => $order_id,
        );
        //查找订单
        $order = $this->orderModel->getOrder($where);
        if(empty($order)){
            echo "fail";exit;
        }
    
        $wechatpay = new PaywechatController();
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        
        file_put_contents("wechatpay2.txt",$xml,FILE_APPEND);
        
        $xml_arr = $wechatpay->xmlToArray($xml);
    
        $res = $wechatpay->checkSign($xml_arr);
    
        if($res == FALSE){
            $r['return_code'] = 'FAIL';
            $r['return_msg'] = '签名失败';
            $a = "签名失败".$order['order_id'];
        }else{
            $r['return_code'] = 'SUCCESS';
            $r['return_msg'] = 'OK';
            $a = "签名正确".$order['order_id'];
        }
        echo $wechatpay->arrayToXml($r);
    
        if($res){
            if ($xml_arr["result_code"] == "SUCCESS") {
                //更改订单状态
                if($order['checked'] == 0){
                    //待支付,更改状态为已支付
                    $this->_changeOrder($order,1,$xml_arr);//更改订单状态为已经支付
                }
    
                $a = "支付成功".$order['order_id'];
    
            }else{
                $a = "支付失败".$order['order_id'];
            }
        }
        
      //  file_put_contents("wechatpay.txt",$a.$xml,FILE_APPEND);exit;
    
    }
    
   
    

    /*
     * 写佣金记录
     * $uid 用户uid
     * $money 佣金金额
     * $content 佣金说明
     * $order 订单数据
     * $from_jibie 来自于第几级别
     分佣的比率
     * $mtype 奖励类型
     * 1分销佣金 ,3现金电子币 ,11大皇冠奖励 12奖励佣金
     */
    protected function _addMoneyLog($uid,$money,$content,$order,$from_jibie,$bili=0,$mtype=1){
        //全部发放到佣金账号
        $yongjin_money = round($money,2);
        
        //判断是否锁定佣金
        $shuoding = C('YONGJIN_LOCK');
        if($mtype == 1){
            if($shuoding == 0){
                //立即发放
                $money_data = array(
                    "money" => array('exp',"money+".$yongjin_money),//佣金
                );

            }else if($shuoding>0){
                //发放到锁定佣金里面
                $money_data = array(
                    "lock_money" => array('exp',"lock_money+".$yongjin_money),//锁定佣金
                );
            }
        }elseif($mtype==12){
            if($shuoding == 0){
                //立即发放
                $this->memberModel->where(array('uid'=>$uid))->setInc('prize_money',$yongjin_money);
            }else if($shuoding>0){
                //发放到锁定佣金里面
                $this->memberModel->where(array('uid'=>$uid))->setInc('lockprize_money',$yongjin_money);
            }
        }elseif($mtype==4){
            $this->memberModel->where(array('uid'=>$uid))->setInc('stock',$yongjin_money);
        }elseif($mtype==2){
            $this->memberModel->where(array('uid'=>$uid))->setInc('score',$yongjin_money);
        }
       
         
        if($money_data){
            $res = $this->updateMemberInfoByuid($uid,$money_data);
            if(!$res){
                return false;
            }
        }
        
    
        //发给对象的信息
        $myinfo = $this->getMemberInfobyUid($uid);
    
        //写佣金流水
        $this->_writeMoneylog($uid,$yongjin_money,$content,$order,$from_jibie,$bili,$mtype,$myinfo,$shuoding);
        
    }
    
    
    /*
     * 写收入流水
     * $mtype 1分销佣金,2重消币 3现金电子币 4重消佣金5互助奖6车房奖7领导奖8分红奖 9保证金 10个税
     */
    protected function _writeMoneylog($uid,$money,$content,$order,$from_jibie,$bili,$mtype,$myinfo,$shuoding){
        
        if($money == 0){
            return false;//金额等于0 不做任何操作
        }
        $myinfo = $this->memberModel->where(array('uid'=>$uid))->find();
        $realname = $myinfo['realname'] ? $myinfo['realname'] : $myinfo['nickname'];
        if($mtype==1){
            $yue = $myinfo["money"]+$myinfo["lock_money"];
            $yue = round($yue,2);
        }elseif($mtype==12){
            $yue = $myinfo["prize_money"]+$myinfo["lockprize_money"];
            $yue = round($yue,2);
        }elseif($mtype==2){
            $yue = $myinfo["score"];
            $yue = round($yue,2);
        }elseif($mtype==4){
            $yue = $myinfo["stock"];
            $yue = round($yue,2);
        }

        $money_log = array(
            "uid" => $myinfo['uid'],
            "nickname" => $realname,
            "logtype" => 1,//收入
            "mtype" => $mtype,//类型
            "money" => $money,
            "content" => $content,
            "order_id" => $order['order_id'],
            "order_uid" => $order['uid'],
            "order_paymoney" => $order['order_cashmoney'],//订单支付的金额(需要分佣的金额)
            "order_nickname" => $order['realname']?$order['realname']:$order['nickname'],
            "pay_time" => $order['pay_time'],//订单支付时间
            "create_time" => date("Y-m-d H:i:s"),//写流水的时间
            "from_jibie" => $from_jibie,
            "bili" => $bili,
            "cash_money" => $yue,//佣金余额,锁定佣金+可提佣金
        );
        
        
        if($shuoding == 0){
            //不锁定
            $money_log['un_lock'] = 1;
        }else{
            //锁定
            $money_log['un_lock'] = 0;
        }
        if($mtype==2) {
            $money_log['un_lock'] = 1;
        }
        $res = $this->moneylogModel->addMoneylog($money_log);
        
        return $res;

    }

    
    
    
   
    
    /*
     * 拼接收入模板
     */
    protected function _shouruTmp($userinfo,$order,$money,$content,$type=0){
        
        $tmp_id = $this->tmpl['FEN_XIAO']['tmp_id'];
	$color = $this->tmpl['FEN_XIAO']['color'];
        
        $url = get_domain()."/mobile/moneylists/money/";
        $footer ="资金已转入你的账户".'\\n\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($content.'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($order['order_sn']),//订单号
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($order['order_cashmoney']),//订单金额
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($money),//订单金额
                    'color' => $color,
                ),
                'keyword4' => array(
                    'value' => urlencode($order['pay_time']),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
        
        return $msg = urldecode(json_encode($msg));
    }
    
    
    /*
     * 收入提醒
     */
    protected function _shouruMsg($userinfo,$order,$money,$content){
    	    //判断是否关注, 没关注就别发了
	    if(!$userinfo['subscribe']){
	        //TODO
	      //  return false;
	    }
	    
        //发送模板消息
        $msg = $this->_shouruTmp($userinfo,$order,$money,$content);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }



    
    public function alipaycallback(){

        $order_id = get('order_id');
        if(!$order_id){
            echo "fail";exit;
        }
        
        $where = array(
            "order_id" => $order_id,
        );
        //查找订单
        $order = $this->orderModel->getOrder($where);
        if(empty($order)){
            echo "fail";exit;
        }

        $data = $_POST;
        $alipay = new PayaliwapController();
        $res = $alipay->checkSign($data);
        
        if($res == FALSE){
            echo "fail";exit;
        }else{
            //签名正确
            echo "success";
        }
        
        if($res){
            if ($data["trade_status"] == "TRADE_SUCCESS") {
                //更改订单状态
                if($order['checked'] == 0){
                    //待支付,更改状态为已支付
                    //$this->_alipaychangeRecharge($order,$data);//更改订单状态为已经完成
                    $this->_changeOrder($order, 3,'',$data);
                }
            }
        }
    }
    

  
    
    

    
 
 
    /**
     * 后台修改订单状态调用这里的函数
     * $memberinfo  在省代报单时应为省代信息   在重复消费时在重消人信息
     * @param unknown $order
     */
    public function adminChangeOrder($order){
        return $this->_changeOrder($order, 6);
    }
    
    /*
     * 后台报单
     */
    public function adminBaodan ($order,$memberinfo,$data) {
        $this->_handleBaodan($order,false);
        $this->_chuli_shengji($memberinfo);
    }


    /*
     * 巴黎庄园增加一个功能：每产生一个订单，把下单人，下单商品，下单金融、当天订单数，当天交易额数据发送到指定999号ID。
     */
    public function sendOrderMsg($order=''){
        
        if(!C('ORDER_ADMIN_UIDS')){
            return false;
        }
        $memwhere = array(
            'uid' => array('in',C('ORDER_ADMIN_UIDS'))
        );
        $memberlist = $this->memberModel->where($memwhere)->select();
        $start = date('Y-m-d 00:00:00');
        
        $where = array(
            'checked' => array('in',array(1,2,5)),
            'pay_time' => array('egt',$start)
        );
        $order['all_ordernumber'] = $this->orderModel->where($where)->count();
        $order['all_ordermoney'] = $this->orderModel->where($where)->sum('pay_orgmoney');
        foreach ($memberlist as $memberinfo){
            $this->_BookMsg($memberinfo, $order);
        }
        
    }
    /*
     * 通知,模板消息
     */
    protected function _BookMsg($userinfo,$khdata){
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg = $this->_sendBookTmp($userinfo,$khdata);
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    

    /*
     * 拼接模板消息
     */
    protected function _sendBookTmp($userinfo,$order){
    
        $tmp_id = $this->tmpl['KH_MSG']['tmp_id'];
        $color = $this->tmpl['KH_MSG']['color'];
        $url = $footer = $header = '';
        $nickname = $userinfo['realname'] ? $userinfo['realname'] : $userinfo['nickname'];
        $header = "新订单提醒".'\\n';
        $header.= "订单标题:".$order['order_title'].'\\n';
        $header.= "下单人姓名:".$order['delivery_name'].'\\n';
        $header.= "下单人手机:".$order['delivery_mobile'].'\\n';
        $header.= "订单金额:".$order['pay_orgmoney'].'\\n';
        $header.= "今日总订单数:".$order['all_ordernumber'].'\\n';
        $header.= "今日订单总金额:".$order['all_ordermoney'].'\\n';
        $url = '';
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($header),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($order['real_name']?$order['real_name']:$order['nickname']),//客户姓名
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode(''),//客户手机
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode(date('Y-m-d H:i:s')),//时间
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
     /*
     * 拼接模板消息
     * 佣金转出
     */
    protected function _tfmoney_tmp($msg_user,$type,$header){
    
        $tmp_id = $this->tmpl['YUE']['tmp_id'];
        $color = $this->tmpl['YUE']['color'];
//        $url = get_domain()."/mobile/moneylists/money/?log_id=".$log_id;
        if($type==1) {
            $left = $msg_user['money'];
        }else if($type==3){
            $left = $msg_user['cash_money'];
        }
//        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $msg_user['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($header),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($msg_user['nickname']),//昵称
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($left),//余额
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),//时间
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
    /*
     * 通知,模板消息
     * 1
     */
    protected function _tfmoney_msg($msg_user,$type,$header){
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$msg_user['subscribe']){
            //return false;
            //TODO
        }
        $msg_user = $this->memberModel->where(array('uid'=>$msg_user['uid']))->find();
        //发送模板消息
        $msg_json = $this->_tfmoney_tmp($msg_user,$type,$header);//拼接模板消息
    
        $msg_data = array(
            "uid" => $msg_user['uid'],
            "openid" => $msg_user['openid'],
            "nickname" => $msg_user['nickname'],
            "groupid" => -1,
            "content" => $msg_json,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msg_data);//添加消息到数据库队列
    
        return true;
    }
    
   
}